1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*!
A parser for `isotope`'s grammar. Generates an AST from input strings.
*/
use crate::ast::*;
use crate::Arc;
use nom::branch::*;
use nom::bytes::complete::{is_a, is_not, tag};
use nom::character::{complete::*, *};
use nom::combinator::*;
use nom::multi::*;
use nom::sequence::*;
use nom::IResult;
use num::BigUint;

mod glyphs;
mod instant;
mod param;
mod primitive;
mod util;
pub use glyphs::*;
pub use instant::*;
pub use param::*;
pub use primitive::*;
pub use util::*;

/// The set of special characters
pub const SPECIAL_CHARACTERS: &str = "\n\r\t :[](){}#\"\\,;~.=*";

/// The keyword for a `let`-statement
pub const LET: &str = "#let";
/// The keyword for a parameter declaration
pub const PARAM: &str = "#param";
/// The keyword for a free instant declaration
pub const INSTANT: &str = "#instant";
/// The keyword for a polymorphic typing universe
pub const UNIVERSE: &str = "#universe";
/// The keyword for lifetimes
pub const LIFETIME: &str = "#lifetime";
/// The keyword for closures
pub const LAMBDA: &str = "#lambda";
/// The keyword for FnCopy function types
pub const FNCOPY: &str = "#fncopy";
/// The keyword for Fn function types
pub const FN: &str = "#fn";
/// The keyword for FnOnce function types
pub const FNONCE: &str = "#fnonce";
/// The keyword for ExCopy function types
pub const EXCOPY: &str = "#excopy";
/// The keyword for Fx function types
pub const FX: &str = "#fx";
/// The keyword for Ex function types
pub const EX: &str = "#ex";
/// The keyword for ExOnce function types
pub const EXONCE: &str = "#exonce";
/// The keyword for FxOnce function types
pub const FXONCE: &str = "#fxonce";
/// The keyword for a live range
pub const LIVE: &str = "#live";
/// The keyword for the beginning of a lifetime
pub const BEGIN: &str = "#begin";
/// The keyword for the end of a lifetime
pub const END: &str = "#end";
/// The empty type
pub const EMPTY: &str = "#empty";
/// The unit type
pub const UNIT: &str = "#unit";
/// The type of natural numbers
pub const NAT: &str = "#nat";
/// The type of boolean
pub const BOOL: &str = "#bool";
/// The true boolean constant
pub const TRUE: &str = "#true";
/// The false boolean constant
pub const FALSE: &str = "#false";
/// The `typeof` operator
pub const TYPEOF: &str = "#typeof";

// General punctuation

/// The symbol for an assignment
pub const ASSIGN: &str = "=";
/// The separator for statements
pub const STMT_SEP: &str = ";";
/// The symbol for a typing judgement
pub const TYPING: &str = ":";
/// The symbol for loosening a typing judgement
pub const LOOSE: &str = "~";

/// Parse an `isotope` expression
///
/// # Examples
/// ```rust
/// # use isotope::parser::expr;
/// # use isotope::ast::Expr::*;
/// // Identifiers
/// assert_eq!(expr("x").unwrap(), ("", Ident("x".to_owned())));
///
/// // Basic constants
/// assert_eq!(expr("0x52").unwrap(), ("", Natural(0x52u64.into())));
/// assert_eq!(expr("#universe[1]").unwrap(), ("", Universe(1)));
/// ```
pub fn expr(input: &str) -> IResult<&str, Expr> {
    alt((
        // Basic expressions
        map(ident, Expr::ident),
        map(sexpr, Expr::Sexpr),
        map(lambda, Expr::Lambda),
        primitive,
        // Type theory
        map(pi, Expr::Pi),
        map(universe, Expr::Universe),
        // Lifetimes
        map(lifetime, Expr::Lifetime),
        // Sugar
        map(scope, Expr::Scope),
        map(typeof_expr, Expr::TypeOf),
    ))(input)
}

/// Parse an `isotope` statement
pub fn statement(input: &str) -> IResult<&str, Statement> {
    alt((
        map(instant, Statement::Instant),
        map(param_stmt, Statement::Param),
        map(let_, Statement::Let),
    ))(input)
}

/// Parse an S-expression
///
/// # Examples
/// ```rust
/// # use isotope::parser::sexpr;
/// # use isotope::ast::{Expr::*, Sexpr};
/// # use smallvec::smallvec;
/// assert_eq!(
///     sexpr("(f x y z)").unwrap(),
///     ("", Sexpr(smallvec![
///         Ident("f".to_owned()).into(),
///         Ident("x".to_owned()).into(),
///         Ident("y".to_owned()).into(),
///         Ident("z".to_owned()).into()
///     ]))
/// );
/// ```
pub fn sexpr(input: &str) -> IResult<&str, Sexpr> {
    map(
        delimited(
            tag("("),
            many0(preceded(opt(ws), map(expr, Arc::new))),
            preceded(opt(ws), tag(")")),
        ),
        |input| Sexpr(input.into()),
    )(input)
}

/// Parse a scope
pub fn scope(input: &str) -> IResult<&str, Scope> {
    map(
        delimited(
            tag("{"),
            pair(
                many0(preceded(opt(ws), statement)),
                delimited(opt(ws), expr, opt(ws)),
            ),
            tag("}"),
        ),
        |(statements, result)| Scope {
            statements,
            result: Arc::new(result),
        },
    )(input)
}

/// Parse a `let` statement
pub fn let_(input: &str) -> IResult<&str, Let> {
    map(
        tuple((
            tag(LET),
            preceded(opt(ws), map_opt(ident, Expr::ident_str)),
            preceded(opt(ws), opt(judgement)),
            preceded(opt(ws), tag(ASSIGN)),
            preceded(opt(ws), expr),
            preceded(opt(ws), tag(STMT_SEP)),
        )),
        |(_, name, judgement, _, value, _)| Let {
            name,
            judgement,
            value: Arc::new(value),
        },
    )(input)
}

/// Parse a typing judgement
pub fn judgement(input: &str) -> IResult<&str, Judgement> {
    map(
        tuple((
            opt(tag(LOOSE)),
            tag(TYPING),
            opt(variance),
            preceded(opt(ws), expr),
        )),
        |(loose, _, variance, expr)| Judgement {
            variance: variance.unwrap_or(Variance::Invariant),
            strict: loose.is_none(),
            ty: Arc::new(expr),
        },
    )(input)
}

/// Parse a typeof expression
pub fn typeof_expr(input: &str) -> IResult<&str, Arc<Expr>> {
    map(preceded(tag(TYPEOF), preceded(opt(ws), expr)), Arc::new)(input)
}

/// Parse a string forming a valid `isotope` identifier
///
/// An `isotope` identifier may be any sequence of non-whitespace characters which does not
/// contain a special character. This parser does *not* consume preceding whitespace!
///
/// # Examples
/// ```rust
/// # use isotope::parser::ident;
/// assert_eq!(ident("hello "), Ok((" ", "hello")));
/// assert!(ident(" bye").is_err());
/// assert!(ident("0x35").is_err());
/// assert_eq!(ident("x35"), Ok(("", "x35")));
/// assert_eq!(ident("你好"), Ok(("", "你好")));
/// let arabic = ident("الحروف العربية").unwrap();
/// let desired_arabic = (" العربية" ,"الحروف");
/// assert_eq!(arabic, desired_arabic);
/// ```
pub fn ident(input: &str) -> IResult<&str, &str> {
    verify(is_not(SPECIAL_CHARACTERS), |ident: &str| {
        !is_digit(ident.as_bytes()[0])
    })(input)
}

/// Parse a typing universe
///
/// # Examples
/// ```rust
/// # use isotope::parser::universe;
/// assert_eq!(universe("#universe[32]"), Ok(("", 32)));
/// assert_eq!(universe("#universe   [  0 ]"), Ok(("", 0)));
/// ```
pub fn universe(input: &str) -> IResult<&str, u64> {
    preceded(
        tag(UNIVERSE),
        delimited(
            delimited(opt(ws), tag("["), opt(ws)),
            u64_dec,
            delimited(opt(ws), tag("]"), opt(ws)),
        ),
    )(input)
}

/// Parse a boolean
///
/// # Examples
/// ```rust
/// # use isotope::parser::boolean;
/// assert_eq!(boolean("#true").unwrap(), ("", true));
/// assert_eq!(boolean("#false").unwrap(), ("", false));
/// assert!(boolean("true").is_err());
/// assert!(boolean("false").is_err());
/// ```
pub fn boolean(input: &str) -> IResult<&str, bool> {
    alt((map(tag(TRUE), |_| true), map(tag(FALSE), |_| false)))(input)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_expressions_parse() {
        let expressions = [
            "(+ x y)",
            "#lambda x: A => y",
            "#fn x: A => B",
            "#fncopy x: A => (B x)",
            "{ #let x = y; #let y = z; (f x y) }",
            "2562",
            "0x523",
            "(+ 24 252)",
            "(f x y (g z))",
            "#fx a : b => (R a)",
            "#fn a : b => (R a)",
            "#empty",
            "()",
            "#unit",
            "#true",
            "#false",
            "#bool",
            "#nat",
        ];
        for e in expressions.iter() {
            let (rest, parse) = expr(e).unwrap();
            assert_eq!(
                rest, "",
                "Expression {:?} not completely parsed! Parse = {:#?}",
                e, parse
            )
        }
    }

    #[test]
    fn invalid_expressions_dont_parse() {
        let expressions = [
            "(+ x y",
            "#lambda x =>",
            "#lambda x : A =>",
            "#lambda x =>",
            "#fn x =>",
            "#begin[(f x y)]",
            "#notakeyword",
            "#let",
            "#let x = y",
            "#let x = y;",
            "{ #let x = y; }",
            "{ #let x = y; x",
        ];
        for e in expressions.iter() {
            let parse = expr(e);
            assert!(
                parse.is_err(),
                "Parse for {:?} should be an error, but got {:#?}",
                e,
                parse
            )
        }
    }

    #[test]
    fn judgements_parse() {
        let judgements = [": a", ":< a", ":* b", "~: c"];
        for &j in &judgements {
            let (rest, _parse) = judgement(j).expect("Valid judgements");
            assert_eq!(rest, "");
        }
    }
}